package com.juno.cafenoa.mypage;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.juno.cafenoa.Constants;
import com.juno.cafenoa.R;
import com.juno.cafenoa.TopNavigatorView;
import com.juno.cafenoa.net.AsyncTaskCompleteListener;
import com.juno.cafenoa.net.HttpPostTask;
import com.juno.cafenoa.util.CafeNoaPreference;
import com.juno.cafenoa.util.Util;

/**
 * passwordActivity와 구조 비슷.
 * 
 * @author JUNHO
 */
public class PasswordConfirmActivity extends Activity implements
		OnClickListener {
	RelativeLayout[] etPassword = new RelativeLayout[4];
	Button[] btnPassword = new Button[12];
	ImageView[] maskPassword = new ImageView[4];

	Button btnBack;
	Button btnCancel;
	TextView text;
	TopNavigatorView navi;
	private boolean firstChar = false;
	private boolean secondChar = false;
	private boolean thirdChar = false;
	private boolean fourthChar = false;
	private String oldPassword;

	private Context mContext;
	private int mode;

	private String password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_password);
		mContext = this;

		navi = (TopNavigatorView) findViewById(R.id.navi_password);
		navi.init("패스워드 설정");

		oldPassword = getIntent().getExtras().getString(
				Constants.USER_PASSWORD_STRING);
		mode = getIntent().getExtras().getInt(Constants.USER_PASSWORD_MODE_SET);

		text = (TextView) findViewById(R.id.passwordTitle);

		text.setText("비밀번호 확인");

		etPassword[0] = (RelativeLayout) findViewById(R.id.password_input1);
		etPassword[1] = (RelativeLayout) findViewById(R.id.password_input2);
		etPassword[2] = (RelativeLayout) findViewById(R.id.password_input3);
		etPassword[3] = (RelativeLayout) findViewById(R.id.password_input4);

		maskPassword[0] = (ImageView) findViewById(R.id.password_mask1);
		maskPassword[1] = (ImageView) findViewById(R.id.password_mask2);
		maskPassword[2] = (ImageView) findViewById(R.id.password_mask3);
		maskPassword[3] = (ImageView) findViewById(R.id.password_mask4);

		btnPassword[0] = (Button) findViewById(R.id.password_number0);
		btnPassword[1] = (Button) findViewById(R.id.password_number1);
		btnPassword[2] = (Button) findViewById(R.id.password_number2);
		btnPassword[3] = (Button) findViewById(R.id.password_number3);
		btnPassword[4] = (Button) findViewById(R.id.password_number4);
		btnPassword[5] = (Button) findViewById(R.id.password_number5);
		btnPassword[6] = (Button) findViewById(R.id.password_number6);
		btnPassword[7] = (Button) findViewById(R.id.password_number7);
		btnPassword[8] = (Button) findViewById(R.id.password_number8);
		btnPassword[9] = (Button) findViewById(R.id.password_number9);

		btnBack = (Button) findViewById(R.id.password_number_back);
		btnCancel = (Button) findViewById(R.id.password_number_cancel);

		btnPassword[0].setOnClickListener(this);
		btnPassword[1].setOnClickListener(this);
		btnPassword[2].setOnClickListener(this);
		btnPassword[3].setOnClickListener(this);
		btnPassword[4].setOnClickListener(this);
		btnPassword[5].setOnClickListener(this);
		btnPassword[6].setOnClickListener(this);
		btnPassword[7].setOnClickListener(this);
		btnPassword[8].setOnClickListener(this);
		btnPassword[9].setOnClickListener(this);
		btnBack.setOnClickListener(this);
		btnCancel.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		if (v == btnPassword[0]) {
			inputNumber(0);
		} else if (v == btnPassword[1]) {
			inputNumber(1);
		} else if (v == btnPassword[2]) {
			inputNumber(2);
		} else if (v == btnPassword[3]) {
			inputNumber(3);
		} else if (v == btnPassword[4]) {
			inputNumber(4);
		} else if (v == btnPassword[5]) {
			inputNumber(5);
		} else if (v == btnPassword[6]) {
			inputNumber(6);
		} else if (v == btnPassword[7]) {
			inputNumber(7);
		} else if (v == btnPassword[8]) {
			inputNumber(8);
		} else if (v == btnPassword[9]) {
			inputNumber(9);
		} else if (v == btnBack) {
			backNumber();
		} else if (v == btnCancel) {
			finish();
		}
	}

	private void backNumber() {
		if (fourthChar) {
			maskPassword[3].setVisibility(View.GONE);
			temp[3] = -2;
			fourthChar = false;
			return;
		}

		if (thirdChar) {
			maskPassword[2].setVisibility(View.GONE);
			temp[2] = -2;
			thirdChar = false;
			return;
		}
		if (secondChar) {
			maskPassword[1].setVisibility(View.GONE);
			temp[1] = -2;
			secondChar = false;
			return;
		}
		if (firstChar) {
			maskPassword[0].setVisibility(View.GONE);
			firstChar = false;
			temp[0] = -2;
		} else {
			finish();
		}
	}

	int[] temp = new int[4];

	private void inputNumber(int num) {

		if (!firstChar) {
			maskPassword[0].setVisibility(View.VISIBLE);
			temp[0] = num;
			firstChar = true;
			return;
		}
		if (!secondChar && temp[0] > -1) {
			maskPassword[1].setVisibility(View.VISIBLE);
			temp[1] = num;
			secondChar = true;
			return;
		}
		if (!thirdChar && temp[1] > -1) {
			maskPassword[2].setVisibility(View.VISIBLE);
			temp[2] = num;
			thirdChar = true;
			return;
		}
		if (!fourthChar && temp[2] > -1) {
			maskPassword[3].setVisibility(View.VISIBLE);
			temp[3] = num;
			// 4자리 모두 입력되었으면.
			// 패스워드를 붙인 후
			// 설정일경우 다음 인텐트로 넘기고
			// 설정이 아닐경우 패스워드가 맞는지 안맞는지 판단하여 return.
			String password = "";
			for (int i = 0; i < temp.length; i++)
				password += String.valueOf(temp[i]);

			if (mode == Constants.PASSWORD_SET_REGEDIT) {
				if (oldPassword.equalsIgnoreCase(password)) {
					Intent intent = new Intent();
					intent.putExtra(Constants.USER_PASSWORD_STRING, password);
					setResult(Constants.REQUEST_PASSWORD_REGEDIT, intent);
					finish();
				} else {
					Toast.makeText(this, "비밀번호가 맞지 않습니다.", Toast.LENGTH_LONG)
							.show();
					for (int i = 0; i < 4; i++)
						maskPassword[i].setVisibility(View.GONE);
					etPassword[0].requestFocus();
					firstChar = false;
					secondChar = false;
					thirdChar = false;
					fourthChar = false;
				}
			} else {
				if (oldPassword.equalsIgnoreCase(password)) {
					this.password = password;
					final String stPd = password;
					AlertDialog.Builder ab = new AlertDialog.Builder(mContext);
					ab.setTitle("주의");
					ab.setMessage("현재 설정된 패스워드는 " + password + "입니다.\n"
							+ "패스워드 분실시 앱 삭제 후 다시 설치해야합니다");
					ab.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									CafeNoaPreference.setUserPassword(mContext, stPd);
									passwdNumChangeListener.excuteHttpTask();
									finish();
								}
							});
					AlertDialog at = ab.create();
					at.show();
				} else {
					Toast.makeText(this, "비밀번호가 맞지 않습니다.", Toast.LENGTH_LONG).show();
					for (int i = 0; i < 4; i++)
						maskPassword[i].setVisibility(View.GONE);
					etPassword[0].requestFocus();
					firstChar = false;
					secondChar = false;
					thirdChar = false;
					fourthChar = false;
				}
			}
		} else {
			Toast.makeText(this, "4자리가 모두 찼습니다.", Toast.LENGTH_SHORT).show();
		}
	}

	AsyncTaskCompleteListener passwdNumChangeListener = new AsyncTaskCompleteListener() {

		@Override
		public void excuteHttpTask() {
			String url = Util.getUrl("MemberInFormChange");

			// name value pair에 id와 password 세팅
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("USER_ID", CafeNoaPreference.getUserID(mContext)));
			value.add(new BasicNameValuePair("USER_NEW_PASSWORD", password));
			value.add(new BasicNameValuePair("USER_CHANGE_FLAG", "P"));
			Log.v("???","password : " + password);
			// httpPostTast 실행.
			HttpPostTask http = new HttpPostTask(mContext, value, url,
					passwdNumChangeListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			if (taskOk) {
				int code = -1;
				String resultString = null;

				try {
					// 코드 받아옴. JSON형태.
					// 파싱하는 과정
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");
					resultString = object.getString("RESULT_STRING");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				// 코드가 내려오지 않은경우는 서버 에러 !
				if (code == -1) {
					Log.v("CafeNoa", "Server Error No code!");
					return;
				}
				if (code == Constants.NETWORK_SUCCESS) {
					Toast.makeText(mContext, "성공적으로 변경되었습니다.",
							Toast.LENGTH_LONG).show();
				}
				Log.v("AccountChange", resultString);
			}
		}

	};
}
